package com.cskaoyan.order.mq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;

/**
 * @Description:
 * @since: 2022-10-28 19:56
 * @author: lazy
 */
@Slf4j
@Component
public class DelyOrderCancelProducer {

    private DefaultMQProducer producer;

    @PostConstruct
    public void init() {
        //1、创建producer对象
        producer = new DefaultMQProducer("order_delay_cancel_producer");
        //2、设置namesrv地址
        producer.setNamesrvAddr("127.0.0.1:9876");
        //3、启动producer
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public boolean sendOrderCancelMessage(String orderId) {
        log.info("start sendDelayOrderMessage {} ...", orderId);
        //4、准备待发送的延迟消息
        Message message = new Message();
        message.setTopic("delay_order");
        message.setBody(orderId.getBytes(Charset.forName("utf-8")));
        //long start = System.currentTimeMillis();
        //message.putUserProperty("startTime",start+"");


        //5、指定消息延迟
        message.setDelayTimeLevel(3);

        SendResult sendResult = null;
        try {
            //6、发送消息
            sendResult = producer.send(message);
        } catch (MQClientException e) {
            e.printStackTrace();

        } catch (RemotingException e) {
            e.printStackTrace();

        } catch (MQBrokerException e) {
            e.printStackTrace();

        } catch (InterruptedException e) {
            e.printStackTrace();

        }

        if (sendResult != null && SendStatus.SEND_OK.equals(sendResult.getSendStatus())) {
            //消息发送成功
            log.info("send {} result success", orderId);
            return true;
        }
        //走到这里说明消息发送失败
        log.info("send {} result fail", orderId);
        return false;
    }
}
